

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="dayu">
  <meta name="keywords" content="">
  
    <meta name="description" content="WebSocket 的引入WebSocket 可以保持着浏览器和客户端之间的长连接， 通过 WebSocket 可以实现数据由后端推送到前 端，保证了数据传输的实时性. WebSocket 涉及到前端代码和后端代码的改造 后端代码的改造WebSocket 的使用 安装 WebSocket 包 npm i ws -S  创建 WebSocket 实例对象 12345const WebSocket &#x3D;">
<meta property="og:type" content="article">
<meta property="og:title" content="数据可视化项目八">
<meta property="og:url" content="http://example.com/2022/11/17/%E6%95%B0%E6%8D%AE%E5%8F%AF%E8%A7%86%E5%8C%96%E9%A1%B9%E7%9B%AE%E4%B8%83/index.html">
<meta property="og:site_name" content="Dayu">
<meta property="og:description" content="WebSocket 的引入WebSocket 可以保持着浏览器和客户端之间的长连接， 通过 WebSocket 可以实现数据由后端推送到前 端，保证了数据传输的实时性. WebSocket 涉及到前端代码和后端代码的改造 后端代码的改造WebSocket 的使用 安装 WebSocket 包 npm i ws -S  创建 WebSocket 实例对象 12345const WebSocket &#x3D;">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-11-17T11:57:08.000Z">
<meta property="article:modified_time" content="2023-09-05T13:21:06.481Z">
<meta property="article:author" content="dayu">
<meta property="article:tag" content="echarts">
<meta name="twitter:card" content="summary_large_image">
  
  
  
  <title>数据可视化项目八 - Dayu</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.3","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 5.4.2"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>dayu</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="数据可视化项目八"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-11-17 19:57" pubdate>
          2022年11月17日 晚上
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          4.9k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          41 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">数据可视化项目八</h1>
            
            
              <div class="markdown-body">
                
                <h1 id="WebSocket-的引入"><a href="#WebSocket-的引入" class="headerlink" title="WebSocket 的引入"></a>WebSocket 的引入</h1><p>WebSocket 可以保持着浏览器和客户端之间的长连接， 通过 WebSocket 可以实现数据由后端推送到前 端，保证了数据传输的实时性. WebSocket 涉及到前端代码和后端代码的改造</p>
<h2 id="后端代码的改造"><a href="#后端代码的改造" class="headerlink" title="后端代码的改造"></a>后端代码的改造</h2><h3 id="WebSocket-的使用"><a href="#WebSocket-的使用" class="headerlink" title="WebSocket 的使用"></a>WebSocket 的使用</h3><ul>
<li><p>安装 WebSocket 包</p>
<p><code>npm i ws -S</code></p>
</li>
<li><p>创建 WebSocket 实例对象</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> <span class="hljs-title class_">WebSocket</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;ws&#x27;</span>)<br><span class="hljs-comment">// 创建出WebSocket实例对象</span><br><span class="hljs-keyword">const</span> wss = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WebSocket</span>.<span class="hljs-title class_">Server</span>(&#123;<br>  <span class="hljs-attr">port</span>: <span class="hljs-number">9998</span>,<br>&#125;)<br></code></pre></td></tr></table></figure></li>
<li><p>监听事件</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs js">wss.<span class="hljs-title function_">on</span>(<span class="hljs-string">&#x27;connection&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">client</span>) =&gt;</span> &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;有客户端连接...&#x27;</span>)<br>  client.<span class="hljs-title function_">on</span>(<span class="hljs-string">&#x27;message&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =&gt;</span> &#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;客户端发送数据过来了&#x27;</span>)<br>    <span class="hljs-comment">// 发送数据给客户端</span><br>    client.<span class="hljs-title function_">send</span>(<span class="hljs-string">&#x27;hello socket&#x27;</span>)<br>  &#125;)<br>&#125;)<br></code></pre></td></tr></table></figure></li>
<li><p>前端的测试代码如下:</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><code class="hljs html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-keyword">html</span>&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">&quot;en&quot;</span>&gt;</span><br>  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">&quot;UTF-8&quot;</span> /&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;viewport&quot;</span> <span class="hljs-attr">content</span>=<span class="hljs-string">&quot;width=device-width, initial-scale=1.0&quot;</span> /&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">&quot;X-UA-Compatible&quot;</span> <span class="hljs-attr">content</span>=<span class="hljs-string">&quot;ie=edge&quot;</span> /&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Document<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span><br>  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span><br>  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;connect&quot;</span>&gt;</span>连接<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;send&quot;</span> <span class="hljs-attr">disabled</span>=<span class="hljs-string">&quot;true&quot;</span>&gt;</span>发送数据<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span><br>    从服务器接收的数据如下:<span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;content&quot;</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="language-javascript"></span><br><span class="language-javascript">      <span class="hljs-keyword">var</span> connect = <span class="hljs-variable language_">document</span>.<span class="hljs-title function_">querySelector</span>(<span class="hljs-string">&#x27;#connect&#x27;</span>)</span><br><span class="language-javascript">      <span class="hljs-keyword">var</span> send = <span class="hljs-variable language_">document</span>.<span class="hljs-title function_">querySelector</span>(<span class="hljs-string">&#x27;#send&#x27;</span>)</span><br><span class="language-javascript">      <span class="hljs-keyword">var</span> content = <span class="hljs-variable language_">document</span>.<span class="hljs-title function_">querySelector</span>(<span class="hljs-string">&#x27;#content&#x27;</span>)</span><br><span class="language-javascript">      <span class="hljs-keyword">var</span> ws = <span class="hljs-literal">null</span></span><br><span class="language-javascript">      connect.<span class="hljs-property">onclick</span> = <span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) &#123;</span><br><span class="language-javascript">        ws = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WebSocket</span>(<span class="hljs-string">&#x27;ws://localhost:9998&#x27;</span>)</span><br><span class="language-javascript">        ws.<span class="hljs-property">onopen</span> = <span class="hljs-function">() =&gt;</span> &#123;</span><br><span class="language-javascript">          <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;连接服务器成功&#x27;</span>)</span><br><span class="language-javascript">          send.<span class="hljs-property">disabled</span> = <span class="hljs-literal">false</span></span><br><span class="language-javascript">        &#125;</span><br><span class="language-javascript">        ws.<span class="hljs-property">onmessage</span> = <span class="hljs-function">(<span class="hljs-params">msg</span>) =&gt;</span> &#123;</span><br><span class="language-javascript">          <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;从服务器接收到了数据&#x27;</span>)</span><br><span class="language-javascript">          content.<span class="hljs-property">innerHTML</span> = msg.<span class="hljs-property">data</span></span><br><span class="language-javascript">        &#125;</span><br><span class="language-javascript">        ws.<span class="hljs-property">onclose</span> = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> &#123;</span><br><span class="language-javascript">          <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;服务器关闭了连接&#x27;</span>)</span><br><span class="language-javascript">          send.<span class="hljs-property">disabled</span> = <span class="hljs-literal">true</span></span><br><span class="language-javascript">        &#125;</span><br><span class="language-javascript">      &#125;</span><br><span class="language-javascript">      send.<span class="hljs-property">onclick</span> = <span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) &#123;</span><br><span class="language-javascript">        ws.<span class="hljs-title function_">send</span>(<span class="hljs-string">&#x27;hello websocket from frontend&#x27;</span>)</span><br><span class="language-javascript">      &#125;</span><br><span class="language-javascript">    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span><br>  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span><br></code></pre></td></tr></table></figure></li>
</ul>
<h3 id="改造后端程序-Koa-Server"><a href="#改造后端程序-Koa-Server" class="headerlink" title="改造后端程序 Koa_Server"></a>改造后端程序 Koa_Server</h3><ul>
<li><p>创建 service\web_socket_service.js 文件</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> <span class="hljs-title class_">WebSocket</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;ws&#x27;</span>)<br><span class="hljs-comment">// 创建出WebSocket实例对象</span><br><span class="hljs-keyword">const</span> wss = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WebSocket</span>.<span class="hljs-title class_">Server</span>(&#123;<br>  <span class="hljs-attr">port</span>: <span class="hljs-number">9998</span>,<br>&#125;)<br><span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span>.<span class="hljs-property">listen</span> = <span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) &#123;<br>  wss.<span class="hljs-title function_">on</span>(<span class="hljs-string">&#x27;connection&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">ws</span>) =&gt;</span> &#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;有客户端连接...&#x27;</span>)<br>    ws.<span class="hljs-title function_">on</span>(<span class="hljs-string">&#x27;message&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =&gt;</span> &#123;<br>      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;客户端发送数据过来了&#x27;</span>)<br>    &#125;)<br>  &#125;)<br>&#125;<br></code></pre></td></tr></table></figure></li>
<li><p>在 app.js 中引入 web_socket_service.js 这个文件, 并调用 listen 方法</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> webSocketService = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;./service/web_socket_service&#x27;</span>)<br>webSocketService.<span class="hljs-title function_">listen</span>()<br></code></pre></td></tr></table></figure></li>
<li><p>约定好和客户端之间数据交互的格式和含义</p>
<ul>
<li><p>客户端和服务端之间的数据交互采用 JSON 格式</p>
</li>
<li><p>客户端发送数据给服务端的字段如下:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs js">&#123;<br><span class="hljs-string">&quot;action&quot;</span>: <span class="hljs-string">&quot;getData&quot;</span>,<br><span class="hljs-string">&quot;socketType&quot;</span>: <span class="hljs-string">&quot;trendData&quot;</span>,<br><span class="hljs-string">&quot;chartName&quot;</span>: <span class="hljs-string">&quot;trend&quot;</span>,<br><span class="hljs-string">&quot;value&quot;</span>: <span class="hljs-string">&quot;&quot;</span><br>&#125;<br>或者<br>&#123;<br><span class="hljs-string">&quot;action&quot;</span>: <span class="hljs-string">&quot;fullScreen&quot;</span>,<br><span class="hljs-string">&quot;socketType&quot;</span>: <span class="hljs-string">&quot;fullScreen&quot;</span>,<br><span class="hljs-string">&quot;chartName&quot;</span>: <span class="hljs-string">&quot;trend&quot;</span>,<br><span class="hljs-string">&quot;value&quot;</span>: <span class="hljs-literal">true</span><br>&#125;<br>或者<br>&#123;<br><span class="hljs-string">&quot;action&quot;</span>: <span class="hljs-string">&quot;themeChange&quot;</span>,<br><span class="hljs-string">&quot;socketType&quot;</span>: <span class="hljs-string">&quot;themeChange&quot;</span>,<br><span class="hljs-string">&quot;chartName&quot;</span>: <span class="hljs-string">&quot;&quot;</span>,<br><span class="hljs-string">&quot;value&quot;</span>: <span class="hljs-string">&quot;chalk&quot;</span><br>&#125;<br></code></pre></td></tr></table></figure>

<p>其中:</p>
<ul>
<li><p>action : 代表某项行为,可选值有</p>
<ul>
<li>getData 代表获取图表数据</li>
<li>fullScreen 代表产生了全屏事件</li>
<li>themeChange 代表产生了主题切换的事件</li>
</ul>
</li>
<li><p>socketType : 代表业务模块类型, 这个值代表前端注册数据回调函数的标识, 可选值有:</p>
<ul>
<li>trendData</li>
<li>sellerData</li>
<li>mapData</li>
<li>rankData</li>
<li>hotData</li>
<li>stockData</li>
<li>fullScreen</li>
<li>themeChange</li>
</ul>
</li>
<li><p>chartName : 代表图表名称, 如果是主题切换事件, 可不传此值, 可选值有:</p>
<ul>
<li>trend</li>
<li>seller</li>
<li>map</li>
<li>rank</li>
<li>hot</li>
<li>stock</li>
</ul>
</li>
<li><p>value : 代表 具体的数据值, 在获取图表数据时, 可不传此值, 可选值有</p>
<ul>
<li>如果是全屏事件, true 代表全屏, false 代表非全屏</li>
<li>如果是主题切换事件, 可选值有 chalk 或者 vintage</li>
</ul>
</li>
</ul>
</li>
<li><p>服务端发送给客户端的数据如下:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs js">&#123;<br><span class="hljs-string">&quot;action&quot;</span>: <span class="hljs-string">&quot;getData&quot;</span>,<br><span class="hljs-string">&quot;socketType&quot;</span>: <span class="hljs-string">&quot;trendData&quot;</span>,<br><span class="hljs-string">&quot;chartName&quot;</span>: <span class="hljs-string">&quot;trend&quot;</span>,<br><span class="hljs-string">&quot;value&quot;</span>: <span class="hljs-string">&quot;&quot;</span>,<br><span class="hljs-string">&quot;data&quot;</span>: <span class="hljs-string">&quot;从文件读取出来的json文件的内容&quot;</span><br>&#125;<br>或者<br>&#123;<br><span class="hljs-string">&quot;action&quot;</span>: <span class="hljs-string">&quot;fullScreen&quot;</span>,<br><span class="hljs-string">&quot;socketType&quot;</span>: <span class="hljs-string">&quot;fullScreen&quot;</span>,<br><span class="hljs-string">&quot;chartName&quot;</span>: <span class="hljs-string">&quot;trend&quot;</span>,<br><span class="hljs-string">&quot;value&quot;</span>: <span class="hljs-literal">true</span><br>&#125;<br>或者<br>&#123;<br><span class="hljs-string">&quot;action&quot;</span>: <span class="hljs-string">&quot;themeChange&quot;</span>,<br><span class="hljs-string">&quot;socketType&quot;</span>: <span class="hljs-string">&quot;themeChange&quot;</span>,<br><span class="hljs-string">&quot;chartName&quot;</span>: <span class="hljs-string">&quot;&quot;</span>,<br><span class="hljs-string">&quot;value&quot;</span>: <span class="hljs-string">&quot;chalk&quot;</span><br>&#125;<br></code></pre></td></tr></table></figure>

<p>注意, 除了 action 为 getData 时, 服务器会在客户端发过来数据的基础之上, 增加 data 字段, 其他的情况, 服务器会原封不动的将从某一个客户端发过来的数据转发给每一个处于连接状态 的客户端</p>
</li>
</ul>
</li>
<li><p>代码实现</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;path&#x27;</span>)<br><span class="hljs-keyword">const</span> fileUtils = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;../utils/file_utils&#x27;</span>)<br><span class="hljs-keyword">const</span> <span class="hljs-title class_">WebSocket</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">&quot;ws&quot;</span>)<br><span class="hljs-comment">// 创建出WebSocket实例对象</span><br><span class="hljs-keyword">const</span> wss = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WebSocket</span>.<span class="hljs-title class_">Server</span>(&#123;<br><span class="hljs-attr">port</span>: <span class="hljs-number">9998</span><br>&#125;)<br><span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span>.<span class="hljs-property">listen</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) &#123;<br>wss.<span class="hljs-title function_">on</span>(<span class="hljs-string">&quot;connection&quot;</span>, <span class="hljs-function"><span class="hljs-params">client</span> =&gt;</span> &#123;<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&quot;有客户端连接...&quot;</span>)<br>client.<span class="hljs-title function_">on</span>(<span class="hljs-string">&quot;message&quot;</span>, <span class="hljs-keyword">async</span> msg =&gt; &#123;<br><span class="hljs-keyword">let</span> payload = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(msg)<br><span class="hljs-keyword">if</span> (payload.<span class="hljs-property">action</span> === <span class="hljs-string">&#x27;getData&#x27;</span>) &#123;<br><span class="hljs-comment">// 返回每个模块的数据</span><br><span class="hljs-keyword">let</span> filePath = <span class="hljs-string">&#x27;../data/&#x27;</span> + payload.<span class="hljs-property">chartName</span> + <span class="hljs-string">&#x27;.json&#x27;</span> <span class="hljs-comment">//</span><br>../data/seller.<span class="hljs-property">json</span><br>filePath = path.<span class="hljs-title function_">join</span>(__dirname, filePath)<br><span class="hljs-keyword">const</span> ret = <span class="hljs-keyword">await</span> fileUtils.<span class="hljs-title function_">getFileJsonData</span>(filePath)<br>payload.<span class="hljs-property">data</span> = ret <span class="hljs-comment">// 增加data字段</span><br>client.<span class="hljs-title function_">send</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(payload))<br>&#125; <span class="hljs-keyword">else</span> &#123;<br><span class="hljs-comment">// 主题切换, 全屏切换, 进行每个客户端的同步, 收到什么数据就发送什么数据</span><br>wss.<span class="hljs-property">clients</span>.<span class="hljs-title function_">forEach</span>(<span class="hljs-function"><span class="hljs-params">client</span> =&gt;</span> &#123;<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&quot;*****************************************&quot;</span>)<br>client.<span class="hljs-title function_">send</span>(message)<br>&#125;)<br>&#125;<br>&#125;)<br>&#125;)<br>&#125;<br></code></pre></td></tr></table></figure></li>
</ul>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E6%95%B0%E6%8D%AE%E5%8F%AF%E8%A7%86%E5%8C%96%E9%A1%B9%E7%9B%AE/" class="category-chain-item">数据可视化项目</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/echarts/">#echarts</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>数据可视化项目八</div>
      <div>http://example.com/2022/11/17/数据可视化项目七/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>dayu</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年11月17日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/11/17/%E6%95%B0%E6%8D%AE%E5%8F%AF%E8%A7%86%E5%8C%96%E9%A1%B9%E7%9B%AE%E5%85%AB/" title="数据可视化项目七">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">数据可视化项目七</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/11/17/%E6%95%B0%E6%8D%AE%E5%8F%AF%E8%A7%86%E5%8C%96%E9%A1%B9%E7%9B%AE%E4%B8%89/" title="数据可视化项目三">
                        <span class="hidden-mobile">数据可视化项目三</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
